const zhiChiSobot = null//uni.requireNativePlugin('zhiChi-SobotKit');
const serviceKey = '3902896fcab749af90adef550a484ad9'
/**
 * 咨询客服
 */
const gotoContactSell = function() {
	
	this.requestAjax({
		url: '/helpCenterApi/getHelpCenterPhoneApi',
		method: 'POST',
		success: function(res) {
			uni.makePhoneCall({
			    phoneNumber: res.data.response || "",
				success: (res) => {
					console.log('调用成功!');
				},
				fail: (res) => {
					console.log('调用失败!');
				}
			});
		}
	});
}


/**
 * 请求接口
 */
const requestAjax = function(params) {
	
	var apiSite = "";
	// #ifndef H5
		// apiSite = "http://49.4.31.246:18000";
		apiSite = "https://api.lianshanggogo.com";
	// #endif
	// #ifdef H5
		apiSite = "/apis";
	// #endif


	if(!params['data']) {
		params['data'] = {};
	}
	
	const tokenInfo = uni.getStorageSync('tokenInfo');
	if (tokenInfo) {
		params['header'] = {
			"Access-Control-Allow-Origin": true,
			"ecp-vt": JSON.parse(tokenInfo)["token"],
			"ecp-vu": JSON.parse(tokenInfo)["customerId"]
		};
	}
	params['data']['random'] = Math.random();
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: apiSite + params['url'],
			method: params['method'],
			header: params['header'] || {},
			data: params['data'] || {},
			success: function(res) {
				resolve(res)
				if(res.data.success || res.data.code == "E_FRT_STORE_NEED_BOUND_TELEPHONE" || res.data.code == 200) {
					params['success'](res);
					
					//验证码特殊处理
					if(params['complate']) {
						params['complate'](res);
					}
				}else {
					if(res.data.code == 'E_NEED_LOGIN') {
						uni.navigateTo({
							url: '/pagesUser/login/userLogin'
						});
					}else {
						console.log(params['url']);
						console.log(res.data.msg);
						uni.showToast({
							title: res.data.msg || params["errorMsg"] || "未知异常",
							icon: "none"
						});
						
						//验证码特殊处理
						if(params['complate']) {
							params['complate'](res);
						}
					}
					reject(res)
				}
			},
			fail: function(res) {
				console.log("fail-----",res)
				reject(res)
			}
		});
	})
}


/**
 * 图片上传
 */
const imgAjax = function(params) {
	
	var apiSite = "";
	// #ifndef H5
		apiSite = "https://v3app.fannybay.net";
	// #endif
	// #ifdef H5
		apiSite = "/apis";
	// #endif
	
	
	if(!params['data']) {
		params['data'] = {};
	}
	
	const tokenInfo = uni.getStorageSync('tokenInfo');
	if (tokenInfo) {
		params['header'] = {
			"Access-Control-Allow-Origin": true,
			"ecp-vt": JSON.parse(tokenInfo)["token"],
			"ecp-vu": JSON.parse(tokenInfo)["customerId"]
		};
	}
	params['data']['random'] = Math.random();
	
	uni.uploadFile({
		url: apiSite + params['url'],
		method: params['method'],
		header: params['header'] || {},
		name: params['name'] || {},
		filePath:params['filePath'] || {},
		success: function(res) {
			let res2 = JSON.parse(res.data);
			if(res2.success) {
				params['success'](res2);
			}else {
				uni.showToast({
					title: res2.data.msg || params["errorMsg"] || "未知异常",
					icon: "none"
				});
			}
		},
		fail: function(res) {
			uni.hideLoading();
		}
	});
}


/**
 * 获取用户信息
 */
const getUserInfo = function(that, succCallBack) {
	return new Promise((resolve, reject) => {
		requestAjax({
			url: "/CustomerApi/findCustomerByCustomerIdForApi",
			method: "POST",
			success: function(res) {
				if(res.data.success) {
					succCallBack ? succCallBack(res) : null;
					resolve(res)
				}else {
					reject(res)
					uni.showToast({
						title: res.data.msg,
						duration: 1500,
						mask: false,
						icon: 'null'
					});
					
				}
			}
		});
	})
	
}


/**
 * 方法拦截器
 */
const methodFilter = function(params) {
	if(!params.that.hasLogin) {
		uni.navigateTo({
			url: '/pagesUser/login/userLogin'
		});
	}else {
		params['success']();
	}
}


// 广告跳转
const adJumpToOtherPage = function(item) {
	
	console.log(item);
	
	// 跳转方式 （10 原生 20 URL 30 富文本 40 无跳转)
	if(item.redirectFlag == 10) {
		
		// 原生页面
		// 原生类型跳转方式（10：商品分类（三级），20：商品详情，30：店铺详情，40：签到，50：领券中心，60：幸运转盘，70：礼品卡首页，80：积分专区，90：会员专区，100：秒杀专区，110：预售专区，120：拼团专区，130：砍价专区，140：订水专区，150：我的余额，160：我的积分，170：余额充值，180：我的推广，190：其它活动专区，200：秒杀专区）
		if(item.jumpType == 10) {
			var tId = item.categoryThird;
			var tName = "分类";
			uni.navigateTo({
				url: '/pages/category/thirdList?categoryId='+tId+'&categoryName='+tName
			});
		}else if(item.jumpType == 20) {
			
			// 2：秒杀活动 5：砍价 6：拼团预售
			if(item.activityType) {
				if(item.activityType == 2) {
					uni.navigateTo({
						url: '/pages/detail/seckill?id='+item.goodsId
					});
				}
				if(item.activityType == 5) {
					uni.navigateTo({
						url: '/pages/detail/bargain?id='+item.goodsId
					});
				}
				if(item.activityType == 6) {
					uni.navigateTo({
						url: '/pages/detail/preGroup?id='+item.goodsId
					});
				}
			}else {
				uni.navigateTo({
					url: '/pages/detail/detail?id='+item.goodsId
				});
			}
		}else if(item.jumpType == 30) {
			uni.navigateTo({
				url: '/pagesGoods/shop/shopDetail?id='+item.vendorId
			});
		}else if(item.jumpType == 50) {
			uni.navigateTo({
				url: '/pagesAccount/coupon/getCoupon'
			});
		}else if(item.jumpType == 60) {
			uni.navigateTo({
				url: '/pagesAccount/signIn/luck'
			});
		}else if(item.jumpType == 80) {
			uni.navigateTo({
				url: '/pagesGoods/specialArea/integralArea'
			});
		}else if(item.jumpType == 90) {
			
			const tokenInfo = uni.getStorageSync('tokenInfo');
			if (!tokenInfo) {
				uni.navigateTo({
					url: '/pagesUser/login/userLogin'
				});
			}else {
				uni.navigateTo({
					url: '/pagesGoods/specialArea/vipArea'
				});
			}
		}else if(item.jumpType == 100) {
			uni.navigateTo({
				url: '/pagesGoods/specialArea/seckillArea'
			});
		}else if(item.jumpType == 120) {
			uni.navigateTo({
				url: '/pagesGoods/specialArea/preGroupArea'
			});
		}else if(item.jumpType == 130) {
			uni.navigateTo({
				url: '/pagesGoods/specialArea/bargainArea'
			});
		}else if(item.jumpType == 140) {
			uni.navigateTo({
				url: '/pagesGoods/specialArea/waterArea'
			});
		}else if(item.jumpType == 150) {
			uni.navigateTo({
				url: '/pagesAccount/balance'
			});
		}else if(item.jumpType == 160) {
			uni.navigateTo({
				url: '/pagesAccount/integral'
			});
		}else if(item.jumpType == 170) {
			uni.navigateTo({
				url: '/pagesAccount/balance'
			});
		}else if(item.jumpType == 180) {
			uni.navigateTo({
				url: '/pagesAccount/extension/extensionDetail'
			});
		}else if(item.jumpType == 190) {
			uni.navigateTo({
				url: '/pagesGoods/specialArea/activityArea?areaId='+item.activityId+'&areaName='+item.areaName
			});
		}else if(item.jumpType == 200) {
			uni.navigateTo({
				url: '/pagesGoods/specialArea/countryArea'
			});
		}else if(item.jumpType == 210 || item.jumpType == 220 ||item.jumpType == 230) {
			//210溯源专区220认证专区230恒量专区，
			uni.navigateTo({
				url: '/pagesGoods/traceability/traceability?jumpType=' + item.jumpType
			});
		}
	}else if(item.redirectFlag == 20) {
		uni.navigateTo({
			url: '/pages/utilPage/webPage?url='+encodeURI(item.pointUrl)
		});
	}else if(item.redirectFlag == 30) {
		uni.navigateTo({
			url: '/pages/utilPage/richText?bannerId='+item.bannerId
		});
	}
}


// 专区banner
const getAreaBanner = function(banner, succCallBack) {
	
	requestAjax({
		url: "/bannerApi/findBannerByTypeApi",
		method: "POST",
		data: {
			// null：全部 10：首页，20会员专区，30秒杀专区，40积分专区，50国家专区，60：预售专区，70：拼团专区，80：砍价专区，90：订水专区，100：幸运转盘，110 启动页
			bannerLocate: banner,
			// 发布终端 ( 20 app 40 pc 50 全部)
			terminal: 50,
			// 类型：null:全部 10 banner 20 功能区(首页) 25 功能区(我的) 30 ads广告位一区 40 ads广告位二区 50 横版广告位
			type: 10
		},
		success: function(res) {
			if(res.data.success) {
				succCallBack(res);
			}else {
				that.$api.msg(res.data.msg || "查询失败");
			}
		}
	});
}


// 推荐商品
const getRecomGoodsList = function(params, succCallBack) {
	
	requestAjax({
		url: "/GoodsApi/recommendedToYouApi",
		method: "POST",
		success: function(res) {
			if(res.data.success) {
				succCallBack(res);
			}else {
				that.$api.msg(res.data.msg || "查询失败");
			}
		}
	});
}


// 富文本格式化
const formatRichText = function(html) {
	
	html = html || "";
	
	//控制小程序中图片大小
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	// newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0 auto;"');
	return newContent;
}


// 剩余时间格式
const leaveTimeFormat = function(leaveTime) {
	
	if(!leaveTime) {
		return "";
	}
	
	var timeStr = "";
	if(leaveTime && leaveTime.split(":").length == 3) {
		var timeArr = leaveTime.split(":");
		if(timeArr[0] > 0) {
			timeStr += (timeArr[0]+"小时");
		}
		if(timeArr[1] > 0) {
			timeStr += (timeArr[1]+"分钟");
		}
		
		return timeStr;
	}
}


// 时间差格式化
const startTimeFormate = function(time, nowTime) {

	console.log(nowTime);
	var now = nowTime || new Date().getTime();
	var minus = (time - now) / 1000;
	
	var day = parseInt(minus / (24 * 60 * 60));
	var dayR = (minus % (24 * 60 * 60));
	
	var hour = parseInt(dayR / (60 * 60));
	var hourR = (minus % (60 * 60));
	
	var minute = parseInt(hourR / 60);
	var minuteR = (minus % 60);
	
	var seconds = parseInt(minuteR % 60);
	
	return {
		year: 0,
		month: 0,
		day: day,
		hour: hour,
		minute: minute,
		seconds: seconds
	};
}


// 购物车数量
const setTabBarBadge = function() {
	
	requestAjax({
		url: '/ShopCartApi/getShopCartCountForApi',
		method: "POST",
		success: function(res) {
			if(res.data.success) {
				
				if(res.data.response > 0) {
					uni.setTabBarBadge({
						index: 2,
						text: res.data.response > 99 ? '99+' : res.data.response+''
					});
				}else {
					uni.removeTabBarBadge({
						index: 2
					});
				}
			}
		},
	});
}


// const openService = (callBack) =>  {
// 	return new Promise((resolve, reject) => {
// 		getUserInfo().then(user => {
// 			console.log("user", user.data.response)
// 			zhiChiSobot.startZhiChi({
// 				app_key: serviceKey,
// 				partnerid: user.data.response.id,
// 				user_nick: user.data.response.nickName,
// 			}, result => {  
// 				// {"desc":"新消息和未读消息数","value":"asd","type":"3","num":1}
// 				uni.setStorageSync('service', result)
// 				console.log(JSON.stringify(result))
// 				callBack(result)
// 				resolve(result)
// 			});
// 		})
// 	})
// }

// 关闭智齿
// const closeService = () => zhiChiSobot.closeSobotChat()

// // 获取消息数量
// const getUnReadMessage = () => {
// 	return new Promise((resolve, reject) => {
// 		getUserInfo().then(user => {
// 			zhiChiSobot.getUnReadMessage({
// 				partnerid: user.data.response.id
// 			}, result => {
// 				// {"desc":"获取未读消息数","value":6,"type":"4"}
// 				console.log(JSON.stringify(result)) 
// 				resolve({
// 					desc: result.desc,
// 					num: result.value,
// 					type: result.type
// 				})
// 			});
// 		});
// 	})
// }

export default {
	gotoContactSell,
	getUserInfo,
	requestAjax,
	imgAjax,
	methodFilter,
	adJumpToOtherPage,
	getAreaBanner,
	getRecomGoodsList,
	formatRichText,
	leaveTimeFormat,
	startTimeFormate,
	setTabBarBadge,
	// openService,
	// getUnReadMessage,
	// closeService,
	serviceKey
}



